package main.listeners;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

public class KeeperContainer {
	
	protected ListenerKeeper keeper;
	protected HashMap<Class<?>, IListenerContainer> containerMap;
	protected HashMap<Class<?>, Collection<?>> listenersMap;
	
	public KeeperContainer(ListenerKeeper keeper) {
		this.keeper = keeper;
		
		containerMap = new HashMap<Class<?>, IListenerContainer>();
		listenersMap = new HashMap<Class<?>, Collection<?>>();
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void addListener(Object l) {
		Class<?> objectClass = l.getClass();
		assert(objectClass.getInterfaces().length == 1);
		Class<?> c = objectClass.getInterfaces()[0];
		
		IListenerContainer container = containerMap.get(c);
		Collection listeners = listenersMap.get(c);
		if(container == null) {
			container = getListenerContainer(c);
			assert(container != null);
			containerMap.put(c, container);
			
			assert(listeners == null);
			listeners = new ArrayList();
			listenersMap.put(c, listeners);
		}
		
		addListener(container, l);
		listeners.add(l);
	}
	
	protected IListenerContainer getListenerContainer(Class<?> c) {
		return keeper.getListenerContainer(c);
	}
	
	protected void addListener(IListenerContainer container, Object l) {
		container.addListener(l);
	}
	
	public void cleanUp() {
		for(Class<?> c : listenersMap.keySet()) {
			Collection<?> listeners = listenersMap.get(c);
			assert(listeners != null);
			assert(!listeners.isEmpty());
			
			for(Object o : listeners) {
				IListenerContainer container = containerMap.get(c);
				assert(container != null);
				
				container.removeListener(o);
			}
		}
	}
}